package org.zh.home.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.zh.home.model.SystemContext;
import org.zh.home.utils.StringUtils;

public class PagerFilter implements Filter {

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		String order = request.getParameter("order");
		if(StringUtils.isBlank(order)) order = "desc";
		SystemContext.setOrder(order);
		
		String sort = request.getParameter("sort");
		if(StringUtils.isBlank(sort)) sort = "id";
		SystemContext.setSort(sort);
		
		String rows = request.getParameter("rows");
		if(StringUtils.isBlank(rows)) rows = "10";
		int pageSize = Integer.parseInt(rows);
		SystemContext.setPageSize(pageSize);
		
		String page = request.getParameter("page");
		if(StringUtils.isBlank(page)) page = "1";
		int pageIndex = Integer.parseInt(page);
		int pageOffset = (pageIndex-1)*pageSize;
		SystemContext.setPageOffset(pageOffset);
		
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {

	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
	}
}
